# -*- coding:utf-8 -*-
# Author  = liuyang
# Time    = 2022/1/7 : 下午4:45
# Target  =
# TODO : 生成视频
# https://blog.csdn.net/DumpDoctorWang/article/details/92399157
import json, codecs, os, time
import cv2

with codecs.open(filename='01.json', mode='r', encoding='utf-8') as fr:
	D = json.load(fr)
	D = [_.replace('/home/liuyang/Desktop/08_ice_tasks/04_KITTI_stereo_3/deploy/video/camera_02/', '/home/liuyang/Desktop/08_ice_tasks/04_KITTI_stereo_3/deploy/video/depth_map/') for _ in D]

image_folder = '/home/liuyang/Desktop/08_ice_tasks/04_KITTI_stereo_3/deploy/video/depth_map'
video_name = 'stereo_3.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
video = cv2.VideoWriter(video_name, fourcc, 5, (width, height))

for image in D:
	print(image)
	img = cv2.imread(image)
	video.write(img)

cv2.destroyAllWindows()
video.release()


# TODO : 生成柱状图
import numpy as np
import matplotlib.pyplot as plt
C3E8 = [0.0556, 0.0518, 0.0721, 0.0999, 0.0473]
C3E9 = [0.0747, 0.0755, 0.0578, 0.1109, 0.0812]
C3E10 = [0.0813, 0.0815, 0.0709, 0.1162, 0.0803]
C3E11 = [0.0840, 0.0829, 0.0766, 0.1280, 0.0988]
C3E12 = [0.1010, 0.0973, 0.1150, 0.1336, 0.1174]

labels = ['abs_rel', '0~20',
		  '20~40', '40~60',
		  '60~80']
X = np.arange(len(C3E8))
plt.figure(figsize=(10, 4))

print(X)
width = 0.15
rects1 = plt.bar(X-width*2, C3E8, width=width, tick_label=labels, color=['red','red','red', 'red', 'red'],alpha=1)
rects2 = plt.bar(X-width*1, C3E9, width=width, tick_label=labels, color=['red','red','red', 'red', 'red'],alpha=0.8)
rects3 = plt.bar(X, C3E10, width=width, tick_label=labels, color=['red','red','red', 'red', 'red'],alpha=0.6)
rects4 = plt.bar(X+width*1, C3E11, width=width, tick_label=labels, color=['red','red','red', 'red', 'red'],alpha=0.4)
rects5 = plt.bar(X+width*2, C3E12, width=width, tick_label=labels, color=['red','red','red', 'red', 'red'],alpha=0.2)
# plt.xticks(rotation=45)
plt.ylabel('abs_rel performance')
plt.xlabel('different range of distance')
plt.title("test dataset performance \n between different range of distance")
plt.ylim(0.0, 0.25)
# plt.show()
plt.legend(['C3E8','C3E9','C3E10', 'C3E11', 'C3E12'])
for a,b in zip(range(len(C3E8)),C3E8):
	plt.text(a-width*2, b+0.001, '%.4f' % b, ha='center', va= 'bottom',fontsize=5)
for a,b in zip(range(len(C3E9)),C3E9):
	plt.text(a-width*1, b+0.001, '%.4f' % b, ha='center', va= 'bottom',fontsize=5)
for a,b in zip(range(len(C3E10)),C3E10):
	plt.text(a, b+0.001, '%.4f' % b, ha='center', va= 'bottom',fontsize=5)
for a,b in zip(range(len(C3E11)),C3E11):
	plt.text(a+width, b+0.001, '%.4f' % b, ha='center', va= 'bottom',fontsize=5)
for a,b in zip(range(len(C3E12)),C3E12):
	plt.text(a+width*2, b+0.001, '%.4f' % b, ha='center', va= 'bottom',fontsize=5)
plt.savefig("bar.png")
# plt.show()

# TODO : 生成折线图
import matplotlib
import matplotlib.pyplot as plt

x = [_ * 2000 for _ in range(len(C3E8))]

# "r" 表示红色，ms用来设置*的大小
plt.plot(x, C3E8, "red", marker='x', ms=5, label='C3E8', alpha=1)
plt.plot(x, C3E9, "red", marker='x', ms=5, label='C3E9', alpha=0.8)
plt.plot(x, C3E10, "red", marker='x', ms=5, label='C3E10', alpha=0.6)
plt.plot(x, C3E11, "red", marker='x', ms=5, label='C3E11', alpha=0.4)
plt.plot(x, C3E12, "red", marker='x', ms=5, label='C3E12', alpha=0.2)
plt.hlines(min(C3E8), min(x), max(x), colors = "blue", linestyles = "dashed", label="C3E8 abs_rel = %.4f"%min(C3E8)    , alpha=1)
plt.hlines(min(C3E9), min(x), max(x), colors = "blue", linestyles = "dashed", label="C3E9 abs_rel = %.4f"%min(C3E9)    , alpha=0.8)
plt.hlines(min(C3E10), min(x), max(x), colors = "blue", linestyles = "dashed", label="C3E10 abs_rel = %.4f"%min(C3E10)    , alpha=0.6)
plt.hlines(min(C3E11), min(x), max(x), colors = "blue", linestyles = "dashed", label="C3E11 abs_rel = %.4f"%min(C3E11)    , alpha=0.4)
plt.hlines(min(C3E12), min(x), max(x), colors = "blue", linestyles = "dashed", label="C3E12 abs_rel = %.4f"%min(C3E12)    , alpha=0.2)

# plt.xticks(rotation=45)
plt.ticklabel_format(axis="x", style="sci", scilimits=(0,0))
plt.xlabel("training iteration")
plt.ylabel("validation dataset abs_rel")
plt.title("training on KITTI dataset \n{camera_02 + Lidar X∈[64, 32, 16, 8, 4]}")
plt.ylim(0.05, 0.20)
# upper left 将图例a显示到左上角
plt.legend(loc="upper right")
# 在折线图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
# for x1, y1 in zip(x, y):
# 	plt.text(x1, y1 + 1, str(y1), ha='center', va='bottom', fontsize=20, rotation=0)
plt.savefig("a.jpg")
plt.show()


# TODO : 生成三维视图
import math
from scipy import ndimage
from PIL import Image


def edges(d):
	dx = ndimage.sobel(d, 0)  # horizontal derivative
	dy = ndimage.sobel(d, 1)  # vertical derivative
	return np.abs(dx) + np.abs(dy)

class PointCloudHelper():
	def __init__(self):
		self.width = 1242
		self.height = 375
		self.focal_X = 7.070493e+02
		self.focal_Y = 7.070493e+02
		self.c_X = 6.040814e+02
		self.c_Y = 1.805066e+02


	def worldCoords(self, depth_map):
		xx, yy = np.tile(range(self.width), self.height).reshape(self.height, self.width), \
				 np.repeat(range(self.height), self.width).reshape(self.height, self.width)
		x_over_z = (self.c_X - xx) / self.focal_X
		y_over_z = (self.c_Y - yy) / self.focal_Y
		z_ndarray = depth_map / np.sqrt(1 + x_over_z ** 2 + y_over_z ** 2)
		x_ndarray = x_over_z * z_ndarray
		y_ndarray = y_over_z * z_ndarray

		xyz_list = np.stack([x_ndarray, z_ndarray, y_ndarray], -1).reshape(-1, 3).tolist()
		return xyz_list


helper = PointCloudHelper()
start_time = time.time()
dense_depth_PATH = "/home/liuyang/Desktop/08_ice_tasks/11_display_3d/data/mono-data/dense_depth/0000000042.png"

depth_map = np.array(Image.open(dense_depth_PATH)) / 256
xyz_list = helper.worldCoords(depth_map)
end_time = time.time()
print(end_time - start_time)
time.sleep(100)
import open3d as o3d

pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz_list)
vis = o3d.visualization.Visualizer()
vis.create_window()
vis.add_geometry(pcd)
view_ctl = vis.get_view_control()
view_ctl.set_front((1, 0, 1))
view_ctl.set_up((0, 0, 1))
view_ctl.set_lookat(pcd.get_center())
vis.run()
# vis.destroy_window()


